/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.ingenic.glass.camera.util;

import java.util.List;

import android.content.Context;
import android.util.Log;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothProfile;

import com.ingenic.glass.camera.CameraAppImpl;
/**
 * 
 */
public class A2DPUtil {
    private static final String TAG = "A2DPUtil";

    private Context mContext;
    private static A2DPUtil sInstance;
    private BluetoothAdapter mBTAdapter;
    private BluetoothA2dp mBluetoothA2dp = null;

    public static A2DPUtil getInstance(Context c) {
	if (null == sInstance)
	    sInstance = new A2DPUtil(c);
	return sInstance;
    }

    public boolean isA2dpPlaying(){
	BluetoothDevice btd = getConnectedDevice();
	return mBluetoothA2dp.isA2dpPlaying(btd);
    }
    private A2DPUtil(Context context){
	if(CameraAppImpl.DEBUG) Log.i(TAG, "new A2DPUtil");
	mContext = context;
	mBTAdapter = BluetoothAdapter.getDefaultAdapter();
	mBTAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.A2DP);

    }

    protected void finalize(){
	mBTAdapter.closeProfileProxy(BluetoothProfile.A2DP,mBluetoothA2dp);
    }

    private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
	    public void onServiceConnected(int profile, BluetoothProfile proxy) {
		if(CameraAppImpl.DEBUG) Log.i(TAG, "onServiceConnected");
		if (profile == BluetoothProfile.A2DP) {
		    mBluetoothA2dp = (BluetoothA2dp) proxy;
		}
	    }
	    public void onServiceDisconnected(int profile) {
		if(CameraAppImpl.DEBUG) Log.i(TAG, "onServiceDisconnected");
		if (profile == BluetoothProfile.A2DP) {
		    mBluetoothA2dp = null;
		}
	    }
	};
    private BluetoothDevice getConnectedDevice(){
	List<BluetoothDevice> lcon =  mBluetoothA2dp.getConnectedDevices();
	for (BluetoothDevice lbt : lcon){
	      if(CameraAppImpl.DEBUG) 
		  Log.d(TAG,"bluetooth device name = "+lbt.getName()+"  bond state="+lbt.getBondState());
	    if (lbt.getBondState() == BluetoothDevice.BOND_BONDED){
		  //Log.i(TAG, "return device name="+lbt.getName());
		return lbt;
	    }
	}
	return null;
    }

}
